<?php
namespace app\modules\v1\services\business;

use app\modules\common\components\Api;
use app\modules\common\components\CacheKey;
use app\modules\common\components\Common;
use app\modules\common\components\RedisStore;
use app\modules\common\exceptions\BusinessException;

use app\modules\common\models\UserModel;
use Exception;
use Yii;

class LoginBusiness
{
    public function doInfo($initData)
    {
        try {
            $userId = $initData['userId'];

            $model = new UserModel();
            $currentInfo = $model->getRowById($userId);
            if (empty($currentInfo)) {
                throw new BusinessException("用户不存在");
            }

            return Common::codeReturn([
                'info' => $currentInfo
            ]);
        } catch (BusinessException $exception) {
            return Common::recordBusinessReturn($exception, __METHOD__);
        } catch (Exception $exception) {
            return Common::recordReturn($exception, __METHOD__);
        }
    }

    public function doLog($initData)
    {
        try {
            $username = $initData['username'];
            $password = $initData['password'];

            $model = new UserModel();
            $currentInfo = $model->getRowByUsername($username);
            if (empty($currentInfo)) {
                throw new BusinessException("用户不存在");
            }

            if ($currentInfo['password'] != $password) {
                throw new BusinessException("用户不存在");
            }

            $info = [
                'userId' => $currentInfo['id']
            ];
            //账户存在

            $sessionId = $model->getSessionId();
            $key = sprintf(CacheKey::LOGIN_INFO, $sessionId);

            $redisStore = new RedisStore(MY_REDIS);
            $redisStore->put($key, $info, 120);

            return Common::codeReturn([
                's' => $sessionId
            ]);
        } catch (BusinessException $exception) {
            return Common::recordBusinessReturn($exception, __METHOD__);
        } catch (Exception $exception) {
            return Common::recordReturn($exception, __METHOD__);
        }
    }
}
